package com.jyl.dptask;

/**
 * 打家劫舍
 *
 * @ClassName P198
 * @Author admin
 * @Date 2024/6/16
 */
public class P198 {

    public static void main(String[] args) {
        //期待结果：4
        int[] nums1 = {1, 2, 3, 1};

        //期待结果：12
        int[] nums2 = {2, 7, 9, 3, 1};

        System.out.println(rob(nums1));
        System.out.println(rob(nums2));

        System.out.println(robByDP(nums1));
        System.out.println(robByDP(nums2));
        System.out.println(robByDP(new int[1]));

        int[] num3 = {9};
        System.out.println(robByDP2(num3));
        System.out.println(robByDP2(nums1));
        System.out.println(robByDP2(nums2));
    }

    protected static int robByDP2(int[] nums) {
        int pre = 0, current = 0, temp;
        for (int num : nums) {
            temp = current;
            current = Math.max(pre + num, current);
            pre = temp;
        }
        return current;
    }

    protected static int robByDP(int[] nums) {
        int length = nums.length;
        if (length == 1) {
            return nums[0];
        }
        if (length == 2) {
            return Math.max(nums[0], nums[1]);
        }
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);

        for (int i = 2; i < length; i++) {
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
        }
        return dp[length - 1];
    }

    public static int rob(int[] nums) {
        return rob(nums, nums.length - 1);
    }

    public static int rob(int[] nums, int end) {
        if (end == 0) {
            return nums[0];
        }
        if (end == 1) {
            return Math.max(nums[0],nums[1]);
        }

        return Math.max(rob(nums, end - 1), rob(nums, end - 2) + nums[end]);
    }

}


















